<template>
    <el-dialog :model-value="dialogVisible" width="1200" :before-close="resetForm" :close-on-click-modal="false">
        <template #header>
            <div class="bold">考试须知</div>
        </template>
        <el-tabs v-model="currentSubject" class="demo-tabs">
            <el-tab-pane v-for="sub in subjects" :key="sub.id" :label="sub.name" :name="sub.id" />
        </el-tabs>
        <div class="dialog-content">
            <el-form ref="ruleFormRef" label-width="auto">
                <el-form-item :label="item.title" v-for="(item, index) in currentSettings" :key="index">
                    <ArtWangEditor v-model="item.details" />
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" :loading="editLoading" @click="submitForm">确认</el-button>
                <el-button @click="resetForm">取消</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { saveSettings, getSettings } from '@/api/driverSchoolApi'

const subjects = [
    { id: '1', name: '科一' },
    { id: '2', name: '科二' },
    { id: '3', name: '科三' },
    { id: '4', name: '科四' }
]

const props = defineProps({
    dialogVisible: {
        type: Boolean
    },
    editInfo: {
        type: Object,
        default: () => {
            id: ''
        }
    }
})

const currentSubject = ref('1')
const emit = defineEmits(['closeDialog'])
const editLoading = ref(false)

const ruleFormRef = ref<FormInstance>()
// 存储所有科目的数据
const allSubjectData = reactive<any>({
    '1': createDefaultSettings('1'),
    '2': createDefaultSettings('2'),
    '3': createDefaultSettings('3'),
    '4': createDefaultSettings('4')
})
const currentSettings = ref<any>(allSubjectData[currentSubject.value])
function createDefaultSettings(subjectId: string): any {
    return [
        {
            title: '考试简介',
            categoryId: subjectId,
            carId: '',
            type: '01',
            details: ''
        },
        {
            title: '考试流程',
            categoryId: subjectId,
            carId: '',
            type: '02',
            details: ''
        },
        {
            title: '考试准备',
            categoryId: subjectId,
            carId: '',
            type: '03',
            details: ''
        },
        {
            title: '注意事项',
            categoryId: subjectId,
            carId: '',
            type: '04',
            details: ''
        }
    ]
}

watch(currentSubject, (newVal) => {
    // 切换到对应科目的数据
    currentSettings.value = allSubjectData[newVal]
})

const submitForm = async () => {
    try {
        editLoading.value = true
        const allSettings = Object.values(allSubjectData).flat()
        const settingVos = allSettings.map((e: any) => ({
            categoryId: e.categoryId,
            carId: props.editInfo.id,
            type: e.type,
            details: e.details
        })).filter(item => item.details)
        let obj = {
            carModelId: props.editInfo.id,
            customImg: props.editInfo.img,
            customStatus: props.editInfo.status,
            settingVos
        }
        const res = await saveSettings(obj)
        if (res.code === '00000') {
            ElMessage.success('修改成功')
            emit('closeDialog', true)
        }
    } catch (e) {
    } finally {
        editLoading.value = false
    }
}

// 获取设置数据并回填
const getSettingsData = async () => {
    try {
        const res = await getSettings(props.editInfo.id)
        if (res.code === '00000' && res.data) {
            const groupedData = groupByCategory(res.data)
            Object.keys(allSubjectData).forEach(subjectId => {
                if (groupedData[subjectId]) {
                    allSubjectData[subjectId] = mergeSettings(
                        allSubjectData[subjectId],
                        groupedData[subjectId]
                    )
                }
            })
            currentSettings.value = allSubjectData[currentSubject.value]
        }
    } catch (error) {
        console.error('获取设置数据失败:', error)
    }
}

function groupByCategory(data: any[]): Record<string, any[]> {
    return data.reduce((acc, item) => {
        const category = item.categoryId
        if (!acc[category]) {
            acc[category] = []
        }
        acc[category].push(item)
        return acc
    }, {})
}

function mergeSettings(defaultSettings: any, apiData: any[]): any {
    return defaultSettings.map((setting: any) => {
        const matchedData = apiData.find(
            (item: any) => item.type === setting.type && item.categoryId === setting.categoryId
        )
        return matchedData ? { ...setting, details: matchedData.details } : setting
    })
}

const resetForm = () => {
    emit('closeDialog')
}

onMounted(() => {
    if (props.editInfo.id) {
        getSettingsData()
    }
})
</script>

<style scoped lang="scss">
/* 内容容器样式 */
.dialog-content {
    height: 62vh;
    display: flex;
    flex-direction: column;
    gap: 20px;
    overflow-y: auto;
    /* 表单项间距 */
}

.bold {
    font-weight: bold;
    color: #333;
}
</style>